package com.eastcode.base.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.eastcode.base.persistence.Manager;
import com.eastcode.base.service.BaseService;
import com.eastcode.base.view.BaseView;
import com.googlecode.objectify.Key;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.Query;

public class BaseServiceImpl implements BaseService {

	/** 保存实体 **/
	public <T> Key<T> save(T entity) {
		Objectify manager = Manager.getPersistenceManager();
		Key<T> key = manager.put(entity);
		return key;
	}

	/** 查找实体 **/
	public <T> T findObjectByKey(Class<T> entityClass, long id) {
		Objectify manager = Manager.getPersistenceManager();
		return manager.get(entityClass, id);
	}

	/** 查找实体列表 **/
	public <T> List<T> searchList(Class<T> entity, BaseView view) {
		Objectify manager = Manager.getPersistenceManager();

		Query<T> query = manager.query(entity);

		Map<String, String> paramMap = view.getParamMap();
		// 组建查询条件
		if (paramMap != null) {
			Iterator<String> iterator = paramMap.keySet().iterator();
			while (iterator.hasNext()) {
				String key = iterator.next();
				query.filter(key, paramMap.get(key));
			}
		}

		// 查询记录条数
		view.setTurnPage(query.count());

		// 分页设置
		int begin = (Integer.parseInt(view.getPageIndex()) - 1) * view.getPerCount();
		query.offset(begin);
		query.limit(view.getPerCount());

		// 排序
		if (view.getOrderByKey() != null && view.getOrderByKey().length() > 0) {
			query.order(view.getOrderByKey());
		}

		// 查询结果
		List<T> result = (List<T>) query.list();

		return result;

	}

	/** 删除实体 **/
	public <T> int deleteObject(T entity) {
		Objectify manager = Manager.getPersistenceManager();

		manager.delete(entity);

		return 0;
	}

	/** 删除实体 **/
	public <T> int deleteObjectByKey(Class<T> entityClass, long id) {
		Objectify manager = Manager.getPersistenceManager();

		T entity = manager.get(entityClass, id);
		manager.delete(entity);

		return 0;
	}

	@Override
	public <T> int deleteObjectBykeys(Class<T> entityClass, String ids) {
		String[] id = ids.split(",");
		Objectify manager = Manager.getPersistenceManager();
		List<T> result = new ArrayList<T>();

		List<String> idList = Arrays.asList(id);
		for (int i = 0; idList != null && i < idList.size(); i++) {
			result.add(manager.get(entityClass, Long.parseLong(idList.get(i))));
		}
		manager.delete(result);

		return 0;
	}
}